package com.zdf.license.verify.config;

import com.zdf.license.verify.model.LicenseAuthInfo;
import com.zdf.license.verify.service.LicenseVerifyService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.InputStream;

/**
 * @author 张德芳
 * @create 2022/6/28 9:57
 */
@ConditionalOnProperty(prefix = "license.verify.handler",name = "enabled",havingValue = "true")
public class LicenseHandlerConfigure {

    @Value("${license.verify.handler.url:/license}")
    private String url;

    /**  查看证书信息 */
    @Bean
    public RouterFunction<ServerResponse> licenseCheckHandle(LicenseVerifyService licenseVerifyService) {
        return RouterFunctions.route(RequestPredicates.GET(url), request -> {
            LicenseAuthInfo licenseAuthInfo = licenseVerifyService.licenseAuthInfo();
            return ServerResponse.ok().body(licenseAuthInfo);
        });
    }

    /** 上传证书 */
    @Bean
    public RouterFunction<ServerResponse> licenseUpdateHandle(LicenseVerifyService licenseVerifyService) {
        return RouterFunctions.route(RequestPredicates.POST(url), request -> {
            try {
                HttpServletRequest httpServletRequest = request.servletRequest();
                if (httpServletRequest.getParts().size() != 1) {
                    return ServerResponse.status(HttpStatus.BAD_REQUEST).body("请选择一个授权文件！");
                }
                for (Part part: httpServletRequest.getParts()) {
                    String fileName = part.getSubmittedFileName();
                    String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if(!(extension.equals("lic"))){
                        return ServerResponse.status(HttpStatus.BAD_REQUEST).body("检查文件类型");
                    }
                    if (part.getSize() == 0) {
                        return ServerResponse.status(HttpStatus.BAD_REQUEST).body("文件异常！");
                    }
                    try (InputStream is = part.getInputStream()) {
                        licenseVerifyService.updateLicense(is);
                    }
                }
                return ServerResponse.ok().body("更新成功!");
            } catch (Exception e) {
                return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
            }
        });
    }
}
